<?php

namespace App\Admin\Controllers;

use App\Models\Module;
use App\Models\Project;
use App\Models\Requirement;
use App\Models\AdminUserRequirement;
use App\Models\AdminUserLog;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Modulebon\Modulebon;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Table;
// use Encore\Admin\Admin;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\Redirect;

class AdminUserRequirementsController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '任务管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new AdminUserRequirement());
        $admin_user_id = Admin::user()->id;
        if($admin_user_id !=1){
            $grid->model()->where('admin_user_id', $admin_user_id);
        }
        $grid->expandFilter();
        $grid->actions(function ($actions) use($admin_user_id){
            if($admin_user_id !=1){
                // 去掉删除
                $actions->disableDelete();
            }
        });
        $grid->model()->orderBy('id', 'desc');
        $grid->column('id', __('Id'));
        $grid->column('requirement_id', __('项目'))->display(function($requirement_id){
            $requirement = Requirement::where('id',$requirement_id)->with('module','module.project')->first();
            return empty($requirement->module->project->name)?'':$requirement->module->project->name;
        });
        $grid->column('requirement.id', __('模块'))->display(function($requirement_id){  
            $requirement = Requirement::where('id',$requirement_id)->with('module')->first();
            return empty($requirement->module->name)?'':$requirement->module->name;
        });
        $grid->column('requirement.name', __('需求简称'));
        $grid->column('adminUser.name', __('执行人'));
        $grid->column('type', __('类型'));
        $grid->column('status', __('状态'));

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(AdminUserRequirement::findOrFail($id));
        $aur = AdminUserRequirement::where('id',$id)->first();
        $show->field('adminUser.name','任务执行人');
        $show->field('status', '状态');
        $show->field('type', '类型');
        $show->field('requirement.name', '需求简称');
        $show->field('requirement.content', '需求说明')->unescape();
        $show->field('requirement.prototype_path', '原型图')->as(function ($prototype_path) {

            return empty($prototype_path)?'无':url('/').'/prototypes/'.$prototype_path;
        
        })->link();
        $show->field('start_time','开始时间');
        $show->field('end_time','结束时间');
        $show->field('times','总耗时');
        $show->field('created_at','创建时间');
        $show->field('updated_at','更新时间');
        
        $show->field('任务记录')->unescape()->as(function ()use($id) {

                $last_log ='';
            $last_log_stcs = (new AdminUserLog)->where('admin_user_requirement_id',$id)->orderBy('date','DESC')->get();

            if(!$last_log_stcs->isEmpty()){
                $last_log .= <<<EOF
                    <table style="border: 1px solid black; border-collapse: collapse;">
                    <tr>
                        <th style="border: 1px solid black;padding: 5px;">日期</th>
                        <th style="border: 1px solid black;padding: 5px;">任务状态</th>
                        <th style="border: 1px solid black;padding: 5px;">计划交付日期</th>
                        <th style="border: 1px solid black;padding: 5px;">停滞原因</th>
                        <th style="border: 1px solid black;padding: 5px;">未开始原因</th>
                        <th style="border: 1px solid black;padding: 5px;">当日耗时</th>
                        <th style="border: 1px solid black;padding: 5px;">预计交付状态</th>
                        <th style="border: 1px solid black;padding: 5px;">已完成比例</th>
                        <th style="border: 1px solid black;padding: 5px;">当日工作内容描述</th>
                    </tr>
                EOF;
                foreach($last_log_stcs as $last_log_stc){
                    $last_log .= "<tr>";
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->date."</td>";//日期
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->status."</td>";//任务状态
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->plan_date."</td>";//计划交付日期
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->stop_reason."</td>";//停滞原因
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->not_start_reason."</td>";//未开始原因
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->times."</td>";//当日耗时
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->give_status."</td>";//交付状态
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->persentage."</td>";//已完成比例
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->description."</td>";//工作内容描述                    
                    // ，任务状态：".$last_log_stc->status.",交付状态：".$last_log_stc->give_status."，耗时：".$last_log_stc->time.($last_log_stc->status!='已完成'?("，已完成比例：".$last_log_stc->persentage."%"):"，已完成比例：100%")."，工作描述：".$last_log_stc->description;
                    
                    $last_log .= "</tr>";
                }
                $last_log .= <<<EOF
                </table>
            EOF;
                return $last_log;
            }else{
                return '空';
            }
        
        });
        $admin_user_id = Admin::user()->id;
        if($admin_user_id !=1 && $aur->admin_user_id != $admin_user_id){
        $show->panel()
            ->tools(function ($tools) {
                $tools->disableEdit();
                
                $tools->disableDelete();
            });
        }
        $show->panel()
        ->tools(function ($tools) {
            $tools->disableDelete();
        });
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new AdminUserRequirement());

        if($form->isEditing()){
            $parameter = request()->route()->parameters();
            $id= $parameter['admin_user_requirement'];
            $aur = AdminUserRequirement::where('id',$id)->with('requirement')->first();
            $admin_user_id = Admin::user()->id;
            if($admin_user_id !=1){
                $form->tools(function (Form\Tools $tools) {
                    // 去掉`删除`按钮
                    $tools->disableDelete();
                });
                
                if($aur->admin_user_id != $admin_user_id){
                    $url = url('/')."/admin/admin_user_requirement/".$id;
                    
                    // 发送永久重定向的HTTP 状态码
                    header("HTTP/1.1 301 Moved Permanently");
                    
                    // 设置重定向地址
                    header("Location: " . $url);
                    
                    // 结束脚本执行
                    exit();
                }
            }

            $form->tools(function (Form\Tools $tools) use($aur) {
                $tools->add('<a class="btn btn-sm btn-primary" href="/admin/requirements/'.$aur->requirement->id.'/edit"><i class="fa fa-trash"></i>&nbsp;&nbsp;需求编辑</a>');
            });
        }

        
        if($form->isEditing()){
            $form->text('adminUser.name','任务执行人')->readonly();
        }else{
            $form->select('admin_user_id','任务执行人')->options('/api/admin_users');
            $form->select('type','类型')->options(['需求讨论' => '需求讨论', '后端开发'=> '后端开发','前端开发'=>'前端开发','UI设计'=>'UI设计','测试'=>'测试','上线部署'=>'上线部署']);
            $form->select('project_id', __('项目'))->options('/api/projects')->load('module_id','/api/modules');
            $form->select('module_id', __('模块'))->load('requirement_id','/api/requirements');
            $form->select('requirement_id', __('需求'));
            $form->ignore(['project_id','module_id']);
        }
        if($form->isEditing()){
            $content = $aur->requirement->content;
            $prototype_path = $aur->requirement->prototype_path;
            $form->html($aur->requirement->name,'需求简称');
            $form->html(!empty($prototype_path)?('<a href="'.url('/').'/prototypes/'.$prototype_path.'" target="_blank" >'.url('/').'/prototypes/'.$prototype_path.'</a>'):'无','原型图');
            $form->html($content,'需求说明');
        }
        $form->radio('status','状态')->options(['未开始' => '未开始', '进行中'=> '进行中','停滞'=>'停滞','已完成'=>'已完成'])->default('未开始');

        $last_log ='';
        if($form->isEditing()){
            $last_log_stcs = (new AdminUserLog)->where('admin_user_requirement_id',$id)->orderBy('date','DESC')->get();

        }

        if(isset($last_log_stcs) && !$last_log_stcs->isEmpty()){
            $last_log .= <<<EOF
                <table style="border: 1px solid black; border-collapse: collapse;">
                <tr>
                    <th style="border: 1px solid black;padding: 5px;">日期</th>
                    <th style="border: 1px solid black;padding: 5px;">任务状态</th>
                    <th style="border: 1px solid black;padding: 5px;">计划交付日期</th>
                    <th style="border: 1px solid black;padding: 5px;">停滞原因</th>
                    <th style="border: 1px solid black;padding: 5px;">未开始原因</th>
                    <th style="border: 1px solid black;padding: 5px;">当日耗时</th>
                    <th style="border: 1px solid black;padding: 5px;">预计交付状态</th>
                    <th style="border: 1px solid black;padding: 5px;">已完成比例</th>
                    <th style="border: 1px solid black;padding: 5px;">当日工作内容描述</th>
                </tr>
            EOF;
            foreach($last_log_stcs as $last_log_stc){
                $last_log .= "<tr>";
                $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->date."</td>";//日期
                $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->status."</td>";//任务状态
                $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->plan_date."</td>";//计划交付日期
                $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->stop_reason."</td>";//停滞原因
                $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->not_start_reason."</td>";//未开始原因
                $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->times."</td>";//当日耗时
                $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->give_status."</td>";//交付状态
                $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->persentage."</td>";//已完成比例
                $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->description."</td>";//工作内容描述                    
                // ，任务状态：".$last_log_stc->status.",交付状态：".$last_log_stc->give_status."，耗时：".$last_log_stc->time.($last_log_stc->status!='已完成'?("，已完成比例：".$last_log_stc->persentage."%"):"，已完成比例：100%")."，工作描述：".$last_log_stc->description;
                
                $last_log .= "</tr>";
            }
            $last_log .= <<<EOF
            </table>
        EOF;
            $form->html($last_log,'任务记录');
        }else{
            $form->html('空','任务记录');
        }
        // 在表单提交前调用
        $form->saving(function (Form $form) {
            $times = $form->times;
            $error = null;  
  
            if (!empty($times) && is_numeric($times)) {  
                // 检查 $times 是否为整数  
                if ((int)$times == $times) {  
                    // $times 是整数，这里您可以根据需要执行操作  
                } else {  
                    // $times 不是整数，检查它是否是一位小数  
                    list($integer, $decimal) = explode('.', $times);  
                    if (isset($decimal) && strlen($decimal) === 1) {  
                        // $times 是一位小数，这里您可以根据需要执行操作  
                    } else {  
                        // $times 不是一位小数  
                        $error = new MessageBag([  
                            'title'   => '耗时错误',  
                            'message' => '必须是整数或一位小数',  
                        ]);  
                    }  
                }  
            } elseif(!empty($times) && !is_numeric($times)) {  
                // $times 不是数字  
                $error = new MessageBag([  
                    'title'   => '耗时错误',  
                    'message' => '必须是数字',  
                ]);  
            }
              
            if ($error) {  
                return back()->with(compact('error'));  
            }  

        });
        return $form;
    }
}
